import React, { useState, useEffect } from 'react';

import { API_BASE_URL_AI } from '../utils/config';
import './ConversationList.css';

interface Conversation {
  _id: string;
  title: string;
  updatedAt: string;
  lastModelId: string;
}

interface ConversationListProps {
  onSelect: (id: string) => void;
  currentId?: string;
}

const ConversationList: React.FC<ConversationListProps> = ({
  onSelect,
  currentId,
}) => {
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchConversations();
  }, []);

  const fetchConversations = async () => {
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE_URL_AI}/conversations`);
      const data = await response.json();
      if (data.success) {
        setConversations(data.data);
      } else {
        setError(data.error || '获取对话列表失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
      console.error('获取对话列表失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleArchive = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      const response = await fetch(
        `${API_BASE_URL_AI}/conversations/${id}/archive`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
        }
      );
      const data = await response.json();
      if (data.success) {
        setConversations(conversations.filter(conv => conv._id !== id));
      } else {
        setError(data.error || '归档对话失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
      console.error('归档对话失败:', err);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (loading) {
    return <div className="conversation-list-loading">加载中...</div>;
  }

  if (error) {
    return <div className="conversation-list-error">{error}</div>;
  }

  return (
    <div className="conversation-list">
      {conversations.length === 0 ? (
        <div className="conversation-list-empty">暂无对话记录</div>
      ) : (
        conversations.map(conv => (
          <div
            key={conv._id}
            className={`conversation-item ${conv._id === currentId ? 'active' : ''}`}
            onClick={() => onSelect(conv._id)}
          >
            <div className="conversation-title">{conv.title}</div>
            <div className="conversation-meta">
              <span className="conversation-time">
                {formatDate(conv.updatedAt)}
              </span>
              <span className="conversation-model">{conv.lastModelId}</span>
            </div>
            <button
              className="conversation-archive"
              onClick={e => handleArchive(conv._id, e)}
              title="归档对话"
            >
              🗑️
            </button>
          </div>
        ))
      )}
    </div>
  );
};

export default ConversationList;
